package com.feihong.txgw.ui.activity.user;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.dtr.settingview.lib.SettingView;
import com.dtr.settingview.lib.entity.SettingData;
import com.dtr.settingview.lib.entity.SettingViewItemData;
import com.dtr.settingview.lib.item.BasicItemViewH;
import com.feihong.txgw.R;
import com.feihong.txgw.inter.contract.user.IUserInfoEditContract;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.user.User;
import com.feihong.txgw.tx_precenter.UserInfoEditMainPrecenter;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.EventBusUtil;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.UserLoginInfo;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static android.support.v4.content.FileProvider.getUriForFile;
import static com.feihong.txgw.utils.UserLoginInfo.getUserInfo;

@RuntimePermissions
public class UserInfoEditeActivity extends BaseMVPCompateActivity<IUserInfoEditContract.AbUserInfoEditMainPrecenter> implements View.OnClickListener, IUserInfoEditContract.IUserInfoEditMainView {

    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.top_back_layout)
    RelativeLayout topBackLayout;
    @BindView(R.id.my_head_img)
    TextView myHeadImg;
    @BindView(R.id.user_right)
    ImageView userRight;
    @BindView(R.id.user_headImg)
    RelativeLayout userHeadImg;
    @BindView(R.id.my_user_info_edit)
    SettingView myUserInfoEdit;
    @BindView(R.id.user_photo_image)
    ImageView userPhotoImage;

    private static final int REQUEST_IMAGE_GET = 0;
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int REQUEST_BIG_IMAGE_CUTTING = 3;
    private static final int REQUEST_SELECT_SEX = 4;
    public static final String IMAGE_FILE_NAME = "icon.jpg";
    public static final String IMAGE_FILE_URL = Environment.getExternalStorageDirectory().getPath() + "/bigIcon/" + IMAGE_FILE_NAME;
    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private static int output_X = 480;
    private static int output_Y = 480;

    private SettingData mItemData = null;
    private SettingViewItemData mItemViewData = null;
    private List<SettingViewItemData> mListData = new ArrayList<SettingViewItemData>();
    BaseBottomDialog dialog = null;
    User user = new User();
    private File photoFilePath;
    private String photoFileUrl;
    private UserEditPhoneDialog mVerifyCarDialog;
    /**
     * 权限申请自定义码
     */
    private final int GET_PERMISSION_REQUEST = 100;
    private int type;

    private RequestOptions mRequestOptions;

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_user_info_edite;
    }

    @Override
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        EventBusUtil.register(this);
        user.setUserPhone(UserLoginInfo.getUserPhone());
        LogUtils.i(TAG + "USERID:" + UserLoginInfo.getUserId());
        setPageTitle("个人资料");
        setBackButtonFinish();

        try {
            //我的头像修改
            userHeadImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog = BottomDialog.create(getSupportFragmentManager())
                            .setLayoutRes(R.layout.take_photo_dialog)
                            // Dialog window 背景色深度 范围：0 到 1，默认是0.2f
                            .setDimAmount(0.5f)
                            // 点击外部区域是否关闭，默认true
                            .setCancelOutside(false)
                            // 设置DialogFragment的tag
                            .setTag("BottomDialog")
                            // 可以进行一些必要对View的操作
                            .setViewListener(new BottomDialog.ViewListener() {
                                @Override
                                public void bindView(View v) {
                                    dialogClick(v);
                                }
                            })
                            .show();
                }
            });
        } catch (Exception e) {
            ToastUtils.getInstance().showShortToast("请重试...");
        }

        myUserInfoEdit.setOnSettingViewItemClickListener(new SettingView.onSettingViewItemClickListener() {
            @Override
            public void onItemClick(int index) {
                switch (index) {
                    case 0:
                        //暂时不做, 这里应该是 click -> 修改用户手机号码
                        showQueryCodeDialog();
                        break;
                    case 1:
                        Intent intent = new Intent(getApplication(), UserEditNickName.class);
                        startActivity(intent);
                        break;
                    case 2:
                        Intent intentSex = new Intent(UserInfoEditeActivity.this, SelectSexActivity.class);
                        startActivityForResult(intentSex, REQUEST_SELECT_SEX);
                        getActivity().overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
//                        changeUserSex();
                        break;
                    case 3:
                        Intent intentAddr = new Intent(getApplication(), MyDeliveryAdrActivity.class);
                        startActivity(intentAddr);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /**
     * 获取验证码
     */
    private void showQueryCodeDialog() {

        if (mVerifyCarDialog != null) {
            mVerifyCarDialog.dismiss();
        }

        LogUtils.i("UserLoginInfo.getUserPhone() : " + UserLoginInfo.getUserPhone());

        mVerifyCarDialog = new UserEditPhoneDialog(UserInfoEditeActivity.this, UserLoginInfo.getUserPhone());
        mVerifyCarDialog.setCancelable(true);
        mVerifyCarDialog.setCanceledOnTouchOutside(true);
        mVerifyCarDialog.showDialog();
    }

    @Override
    public void bindData() {

        mRequestOptions = new RequestOptions()
                .error(R.mipmap.user_head)
                .placeholder(R.mipmap.user_head);

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("手机号");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);
        mItemData.setSubTitle(UserLoginInfo.getUserPhone());

        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("昵称");
        mItemData.setTitleSize(14);
        if (!TextUtils.isEmpty(getUserInfo().getUserName())) {
            mItemData.setSubTitle(getUserInfo().getUserName());
        } else {
            mItemData.setSubTitle("");
        }

        mItemData.setSubTitleSize(12);

        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("性别");
        mItemData.setTitleSize(14);

        mItemData.setSubTitleSize(12);
        String sex = getUserInfo().getUserSex();
        if (!sex.isEmpty()) {
            switch (Integer.parseInt(sex)) {
                case 1:
                    mItemData.setSubTitle("男");
                    break;
                case 2:
                    mItemData.setSubTitle("女");
                    break;
                default:
                    mItemData.setSubTitle("保密");
                    break;
            }
        }

        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("收货地址");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        myUserInfoEdit.setAdapter(mListData);

        //头像显示
        if (!UserLoginInfo.getUserInfo().getUserPic().isEmpty()) {
            //头像显示

            Glide.with(getApplicationContext()).load(UserLoginInfo.getUserInfo().getUserPic()).apply(mRequestOptions).into(userPhotoImage);
        }
    }

    @Override
    public void onUserLogin(LoginMessage message) {
        switch (message.getAction()) {
            case LoginMessage.ACTION_LOGIN:
                if ("name".equals(message.getUser_type())) {
                    myUserInfoEdit.modifySubTitle(UserLoginInfo.getUserInfo().getUserName(), 1);
                }
                break;
            case LoginMessage.ACTION_CANCEL:
                break;
            case LoginMessage.ACTION_EXIT:
                break;
            default:

                break;
        }
    }


    private int mEditStatus;

    private void updateSex(String newSex) {
        String saveSex = UserLoginInfo.getUserInfo().getUserSex();
        if (!newSex.equals(saveSex)) {
            user.setUserSex(newSex);
            mEditStatus = 2;
            editInfoPost(mEditStatus, newSex);
        } else {
            ToastUtils.getInstance().showLongToast("信息保存成功");
        }
    }

    @Override
    public void onClick(View v) {
        //相同就不更新

        switch (v.getId()) {

            case R.id.user_take_photo:
                //6.0动态权限获取
                type = 0;
//                getPermissions();
                UserInfoEditeActivityPermissionsDispatcher.queryUserImgFileWithCheck(this);
                dialogCancel();
                break;
            case R.id.user_select_from_lib:
                //6.0动态权限获取
                type = 1;
                UserInfoEditeActivityPermissionsDispatcher.queryUserImgFileWithCheck(this);
                dialogCancel();
                break;

            case R.id.user_photo_cancel:

                dialogCancel();
                break;
            default:
                break;
        }

    }

    private void dialogClick(View v) {

        v.findViewById(R.id.user_take_photo).setOnClickListener(this);

        v.findViewById(R.id.user_select_from_lib).setOnClickListener(this);

        v.findViewById(R.id.user_photo_cancel).setOnClickListener(this);
    }

    private void doNext(int requestCode, int[] grantResults) {
        LogUtils.i(TAG + "555:" + type);
        if (requestCode == GET_PERMISSION_REQUEST) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED & grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                if (type == 0) {
                    takePhotoIntent();
                } else {
                    selectFrom();
                }
            } else {
                Toast.makeText(this, "请在应用管理中打开应用访问权限！", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

    private void takePhotoIntent() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            File newFile = new File(getExternalCacheDir().getAbsolutePath(), IMAGE_FILE_NAME);
            Uri contentUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                contentUri = getUriForFile(this,
                        "com.feihong.txgw.updatefileprovider", newFile);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                contentUri = Uri.fromFile(newFile);
            }

            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    contentUri);
            startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        } else {
            ToastUtils.getInstance().showShortToast("相机开启失败");
            finish();
        }
    }

    private void selectFrom() {
//        PhotoPicker.builder().setPhotoCount(1)
//                .setShowCamera(true)
//                .setShowGif(false)
//                .setPreviewEnabled(false)
//                .start(getActivity(), REQUEST_IMAGE_GET);

//        String cachePath = getApplicationContext().getExternalCacheDir().getPath();
//        imageFile = new File(cachePath,"head.jpg");
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
////        Intent intent = new Intent(Intent.ACTION_PICK, null);
////        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        intent.setType("image/*");
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            //如果大于等于7.0使用FileProvider
//            uriForFileUri = FileProvider.getUriForFile(getActivity(), "com.feihong.txgw.updatefileprovider", imageFile);
//            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        } else {
//            uriForFileUri = Uri.fromFile(imageFile);
//        }
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uriForFileUri);
        Intent albumIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(albumIntent, REQUEST_IMAGE_GET);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    /**
     * 处理回调结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 回调成功
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 大图切割
                case REQUEST_BIG_IMAGE_CUTTING:
                    if (data != null) {
                        setPicToView();
                    }
                    break;

                // 相册选取
                case REQUEST_IMAGE_GET:
                    startBigPhotoZoom(data.getData());
                    break;
                // 拍照
                case REQUEST_IMAGE_CAPTURE:
                    startBigPhotoZoom(null);
                    break;
                case REQUEST_SELECT_SEX:
                    if (data != null) {
                        if (SelectSexActivity.MAN_VALUE == data.getIntExtra(SelectSexActivity.SELECT_SEX_KEY, 0)) {
                            mCurrentSex = "1";
                            updateSex(mCurrentSex);
                        } else if (SelectSexActivity.WOMEN_VALUE == data.getIntExtra(SelectSexActivity.SELECT_SEX_KEY, 0)) {
                            mCurrentSex = "2";
                            updateSex(mCurrentSex);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private String mCurrentSex = null;

    /**
     * 大图模式切割图片
     * 直接创建一个文件将切割后的图片写入
     */
    public void startBigPhotoZoom(Uri uri) {
        Uri contentUri;
        File sourceFile = new File(getExternalCacheDir(), IMAGE_FILE_NAME);
        if(uri != null){
            // 相册
            contentUri = uri;
        }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 7.0拍照
            contentUri = getUriForFile(this,
                    "com.feihong.txgw.updatefileprovider",
                    sourceFile);
            Log.i(TAG, "startBigPhotoZoom: " + contentUri);
        }else {
            // 6.0拍照
            contentUri = Uri.fromFile(sourceFile);

        }

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String storage = getApplicationContext().getExternalCacheDir().getPath();
            File dirFile = new File(storage + "/bigIcon");
            if(!dirFile.exists()){
                dirFile.mkdirs();
            }
            photoFilePath = new File(dirFile, IMAGE_FILE_NAME);
            Uri desUri = Uri.fromFile(photoFilePath);
            // 开始切割
            Intent intent = new Intent("com.android.camera.action.CROP");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            intent.setDataAndType(contentUri, "image/*");
            intent.putExtra("crop", "true");
            // 裁剪框比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // 输出图片大小
            intent.putExtra("outputX", output_X);
            intent.putExtra("outputY", output_Y);
            intent.putExtra("scale", true);
            // 不直接返回数据
            intent.putExtra("return-data", false);
            // 返回一个文件
            intent.putExtra(MediaStore.EXTRA_OUTPUT, desUri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            startActivityForResult(intent, REQUEST_BIG_IMAGE_CUTTING);
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        }
    }


    /**
     * 保存图片后，设置到视图中
     */
    private void setPicToView() {

        // 创建 smallIcon 文件夹
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            Bitmap photoBitmap;
            // 保存图片
            FileOutputStream outputStream = null;
            try {
                Log.i(TAG, "setPicToView: 开始保存图片");
                // 读取uri所在的图片
                photoBitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), Uri.fromFile(photoFilePath));

                outputStream = new FileOutputStream(photoFilePath);

                LogUtils.d(TAG + "photoFilePath:文件保存" + photoFilePath.getPath());
                photoBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                outputStream.flush();

                Log.i(TAG, "setPicToView: 开始压缩");
                LogUtils.d(TAG + "extras:文件压缩");
                Luban.with(this)
                        //传人要压缩的图片
                        .load(photoFilePath)
                        //设置回调
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                // TODO 压缩开始前调用，可以在方法内启动 loading UI
                            }

                            @Override
                            public void onSuccess(File file) {
                                // TODO 压缩成功后调用，返回压缩后的图片文件
                                LogUtils.d(TAG + "压缩成功后调用，返回压缩后的图片文件" + file.getPath());
                                //上传图片,返回Url
                                LogUtils.d(TAG + "上传图片,返回Url" + file);

                                RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                                MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData("idcard_img_file", file.getName(), imageBody);
                                mPresenter.upLoadUserImg(imageBodyPart);
                            }

                            @Override
                            public void onError(Throwable e) {
                                // TODO 当压缩过程出现问题时调用
                                e.printStackTrace();
                                ToastUtils.getInstance().showShortToast("保存失败,请稍后尝试~");
                            }
                        }).launch();    //启动压缩

            } catch (Exception e) {
                e.printStackTrace();
                ToastUtils.getInstance().showShortToast("保存失败,请稍后尝试~");
                return;
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    /**
     * 信息更新post
     *
     * @param type 用户信息修改类别  用户信息修改(1.用户头像,2..用户性别,3.用户昵称)
     * @param info 修改的数据
     */
    private void editInfoPost(int type, String info) {
        mPresenter.getUserInfo(String.valueOf(type), info);
    }

    private void dialogCancel() {
        dialog.dismiss();
    }

    @NeedsPermission({android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void queryUserImgFile() {
        if (type == 0) {
            takePhotoIntent();
        } else {
            selectFrom();
        }
    }

    @OnPermissionDenied({android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void queryImgFileDenied() {
        dialogCancel();
//        Toast.makeText(this,"")
        showDialog("权限不足", "您没有开启此应用的使用权限。请到系统设置-->权限管理 开启相机和存储使用权限。", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialog.cancel();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        UserInfoEditeActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    public void UserIconRationaleForCamera(final PermissionRequest request) {
        request.proceed();
//        new AlertDialog.Builder(this)
//                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(@NonNull DialogInterface dialog, int which) {
//                        request.proceed();
//                    }
//                })
//                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(@NonNull DialogInterface dialog, int which) {
//                        request.cancel();
//                    }
//                })
//                .setCancelable(false)
//                .setMessage("请允许获取相机、本地读写权限")
//                .show();
    }

    @Override
    public void getUserInfoResult(String result) {
        try {
            if (activityIsDestory()) {
                return;
            }
            JSONObject json = JSONObject.parseObject(result);

            //成功
            if ("200".equals(json.get("code").toString())) {

                if (!UserLoginInfo.saveUserLoginInfo(user)) {
                    LogUtils.i(TAG + "--------userInfoEdit(name)-------保存失败");
                }

                //更新状态
                if (mEditStatus == 1) {
                    //本地地址
                    userPhotoImage.setImageURI(Uri.fromFile(photoFilePath));

                    LoginMessage login = new LoginMessage();
                    login.setAction(LoginMessage.ACTION_LOGIN);
                    login.setUser_type("photo");
                    EventBus.getDefault().post(login);

                    //头像显示
                    Glide.with(getApplicationContext()).load(UserLoginInfo.getUserInfo().getUserPic()).apply(mRequestOptions).into(userPhotoImage);
                }
                if (mEditStatus == 2) {
                    String newSexStr = "保密";
                    switch (Integer.parseInt(mCurrentSex)) {
                        case 1:
                            newSexStr = "男";
                            break;
                        case 2:
                            newSexStr = "女";
                            break;
                        default:
                            newSexStr = "保密";
                            break;
                    }
                    myUserInfoEdit.modifySubTitle(newSexStr, 2);
                }

                ToastUtils.getInstance().showShortToast("保存成功!");
            } else {
                ToastUtils.getInstance().showShortToast("信息保存失败,请重试~");
            }
        } catch (Exception err) {

        }
    }

    @Override
    public void getUserInfoError() {
        showSystemToast(getString(R.string.connect_service_error));
    }

    @Override
    public void upLoadUserImgResult(String result) {

        try {
            if (activityIsDestory()) {
                return;
            }
            LogUtils.i(TAG + "CommonCallback:" + result);
//
            JSONObject json = JSONObject.parseObject(result);

            //成功
            if ("1".equals(json.get("status").toString())) {
                //上传成功 ,返回地址
                photoFileUrl = json.getString("filename");
                user.setUserPic(photoFileUrl);
                mEditStatus = 1;
                //保存图片数据，并设置头像部分的View
                editInfoPost(mEditStatus, photoFileUrl);
            } else {
                ToastUtils.getInstance().showShortToast("头像修改失败,请重试~");
            }
        } catch (Exception err) {
            err.printStackTrace();
        }
    }

    @Override
    public void upLoadUserImgError() {

    }

    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {
        showSystemToast(getString(R.string.connect_service_error));
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return UserInfoEditMainPrecenter.create();
    }
}
